{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "539fea39-ee4d-4ce6-a8ef-c9237f914edc",
   "metadata": {},
   "source": [
    "### 背包问题"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "810002c3-3208-437c-930a-1457511a5159",
   "metadata": {},
   "source": [
    "**问题定义：背包问题**\n",
    "\n",
    "**输入**：物品价值$v_1,v_2,…,v_n$；物品大小$s_1,s_2,…,s_n$；背包容量$C$（所有的值均为正整数）。\n",
    "\n",
    "**输出**：一个物品子集$S \\subseteq \\{ 1, 2,…,n \\}$ ，具有最大的价值之和$\\sum_{i \\in S} v_i$，但必须满足总大小$\\sum_{i \\in S} s_i$ 不超过 $C$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3eeb7578-b54f-4aab-9a24-e4be152a5f5f",
   "metadata": {},
   "source": [
    "考虑下面这个背包问题的实例，背包的容量C= 6并且有4件物品\n",
    "\n",
    "| 物品 | 价值 | 大小 |\n",
    "| ---- | ---- | ---- |\n",
    "| 1    | 3    | 4    |\n",
    "| 2    | 2    | 3    |\n",
    "| 3    | 4    | 2    |\n",
    "| 4    | 4    | 3    |\n",
    "\n",
    "最优解决方案的总价值是多少呢？"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "246d7e45-271a-4c2a-a903-c1af56873cee",
   "metadata": {},
   "source": [
    "为了在背包问题中应用动态规划，我们必须推断出正确的子问题集合。  \n",
    "为了实现这个目标，我们需要推断出最优解决方案的结构，并确认从更小子问题的最优解决方案构造更大子问题解决方案的不同方式。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d69a2e8c-b9d3-4318-99b4-eb3843c80676",
   "metadata": {},
   "source": [
    "这种操作的另一个成果是一个推导公式，它可以从两个更小子问题的解决方案中计算出一个更大子问题的解决方案。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea6cd021-27b4-445f-9041-1f3321683b4e",
   "metadata": {},
   "source": [
    "这个最优解决方案看上去应该是怎么样的呢？\n",
    "我们可以从一个思路出发：$S$ 要么包含了最后一件物品（物品 $n$），要么不包含它。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78d68f9c-3700-4a93-97d5-f286c60720e7",
   "metadata": {},
   "source": [
    "**背包问题的最优子结构**\n",
    "\n",
    "设$S$是具有$n≥1$件物品、物品价值$v_1,v_2,…,v_n$、物品大小$s_1,s_2,…,s_n$、背包容量$C$的背包问题的最优解决方案。\n",
    "则$S$必为下面两者之一："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80b22084-c812-42b3-a141-245bac987e3a",
   "metadata": {},
   "source": [
    "（a）由前$n - 1$件物品组成的背包容量为$C$的子问题的最优解决方案。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab0e03f0-129c-472b-b834-a2f3d93fa36f",
   "metadata": {},
   "source": [
    "（b）由前$n - 1$件物品组成的背包容量为$C - s_n$的子问题的最优解决方案再加上最后一件物品$n$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f5692d9-82b1-4cc2-87e0-af41b8b45e33",
   "metadata": {},
   "source": [
    "（a）的解决方案总是最优解决方案的选项之一。（b）的解决方案当且仅当$s_n≤C$时才是选项之一。  \n",
    "在这种情况下，可以有效地预先为物品$n$保留$s_n$个单位的容量。具有更大总价值的那个选项就是最优解决方案，从而形成下面的推导公式。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1335299-28dc-48b2-9b3b-4866e12fbbe2",
   "metadata": {},
   "source": [
    "**背包问题的推导公式**\n",
    "\n",
    "根据**背包问题的最优子结构**的假设和说明，设$V_{i,c}$表示总大小不超过$c$的前$i$件物品所组成的子集的最大总价值\n",
    "（当$i = 0$时，$V_{i,c}$可以看成$0$）。对于每个$i = 1, 2,…, n$和$c = 0, 1, 2,…, C$：\n",
    "\n",
    "$V_{i,c} = \\begin{cases} \\underbrace{V_{i-1,c}}_{情况1} & S_i > c \\\\ max \\{ \\underbrace{V_{i-1,c}}_{情况1}, \\underbrace{V_{i-1,c-s_i} + v_i}_{情况2} \\} & S_i \\le c \\end{cases}$\n",
    "\n",
    "由于$c$和物品的大小都是整数，因此第二个表达式中的剩余容量$c - s_i$也是整数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7969428-e4f3-490a-bbcc-f480914c7e5d",
   "metadata": {},
   "source": [
    "下一个步骤是定义相关子问题的集合，并使用**背包问题的推导公式**系统地解决这些子问题。至于现在，我们把注意力集中在计算每个子问题的最优解决方案的总价值上。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93b30d36-de3e-409e-9c85-fef8e2d5ffb2",
   "metadata": {},
   "source": [
    "对于背包问题，子问题应该由两个索引进行参数化：前几个物品的长度$i$和可用的背包容量$c$。对两个参数所有相关的值均加以考虑，我们就可以得到子问题。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d371b6c-b994-440d-8e2f-8351c2f6a0cf",
   "metadata": {},
   "source": [
    "**背包问题的子问题**\n",
    "\n",
    "计算前$i$个物品和背包容量为$c$的最优背包解决方案的总价值$V_{i,c}（i =0,1,2,…,n，c=0,1,2,…, C）$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb3ca109-2e7f-4484-99a4-c5eedba6c13a",
   "metadata": {},
   "source": [
    "最大子问题$（i = n且c = C）$就与原问题相同。由于所有物品的大小和背包容量$C$都是正整数，并且由于容量总是会减去某个物品的大小（为它保留空间），因此剩下的容量只可能在$0～C$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26056834-8b25-4552-891f-79c77b465df3",
   "metadata": {},
   "source": [
    "明确了子问题和推导公式之后，我们立即就能想到背包问题的一种动态规划算法。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dccf0ec4-24f6-40e1-a9a1-aad10ed4bc66",
   "metadata": {},
   "source": [
    "**算法：背包问题**\n",
    "\n",
    "**输入**：物品价值$v_1,v_2,…,v_n$，物品大小$s_1,s_2,…,s_n$和背包容量$C$（均为正整数）。\n",
    "\n",
    "**输出**：具有最大总价值的子集$S \\subseteq \\{ 1, 2,…,n \\}$ ，满足总大小$\\sum_{i \\in S} s_i \\le C$。\n",
    "\n",
    "---\n",
    "\n",
    "// 子问题的解决方案（索引从0开始）  \n",
    "$A := (n + 1) \\times (C + 1) $二维数组  \n",
    "// 基本情况（$i = 0$）  \n",
    "**for** c = 0 to C **do**   \n",
    "&emsp;&emsp;$A[0][c] = 0$  \n",
    "//系统性地解决所有的子问题  \n",
    "**for** i = 1 to n **do**  \n",
    "&emsp;&emsp;**for** c = 0 to C **do**  \n",
    "&emsp;&emsp;&emsp;&emsp;// 使用**背包问题的推导公式**  \n",
    "&emsp;&emsp;&emsp;&emsp;**if** $s_i$ > c **then**  \n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;$A[i][c] := A[i − 1][c]$  \n",
    "&emsp;&emsp;&emsp;&emsp;**else**  \n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;$A[i][c] := max \\{ \\underbrace{A[i-1][c]}_{情况1}, \\underbrace{A[i-1][c-s_i] + v_i}_{情况2} \\}$  \n",
    "**return** $A[n][C]$  \n",
    "//最大子问题的解决方案  \n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d66f63ca-1a02-4243-b760-3ec91f5520c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def knapsack(weights, values, capacity):\n",
    "    assert len(weights) == len(values), \"物品价值数组长度必须等于物品大小数组\"\n",
    "    n = len(weights)\n",
    "    A = [[0 for _ in range(capacity+1)] for _ in range(n+1)]\n",
    "    for c in range(capacity+1):\n",
    "        A[0][c] = 0\n",
    "\n",
    "    for i in range(1, n+1):\n",
    "        for c in range(0, capacity+1):\n",
    "            if weights[i-1] > c:\n",
    "                A[i][c] = A[i-1][c]\n",
    "            else:\n",
    "                A[i][c] = max(A[i-1][c], A[i-1][c-weights[i-1]] + values[i-1])\n",
    "\n",
    "    return A[n][capacity]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4113df6c-aa85-461e-9102-0843c3cbfed3",
   "metadata": {},
   "source": [
    "现在，数组A是一个二维数组，反映了对子问题进行参数化时所使用的索引$i$和$c$。  \n",
    "当双重for循环的一次迭代必须计算子问题解决方案$A[i][c]$时，\n",
    "两个相关的更小子问题的值$A[i−1][c]$和$A[i−1][c−s_i]$在外层循环之前的一次迭代时（或作为基本情况）已经计算出来了。\n",
    "我们可以得出结论，这个算法花费$O(1)$的时间解决$(n + 1)(C + 1) = O(nC)$个子问题中的每一个，因此总体运行时间是$O(nC)$。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43bc24cc-6934-4a58-9602-e3ad2ebb9432",
   "metadata": {},
   "source": [
    "**示例**\n",
    "\n",
    "考虑下面这个背包问题的实例，背包的容量C= 6并且有4件物品\n",
    "\n",
    "| 物品 | 价值 | 大小 |\n",
    "| ---- | ---- | ---- |\n",
    "| 1    | 3    | 4    |\n",
    "| 2    | 2    | 3    |\n",
    "| 3    | 4    | 2    |\n",
    "| 4    | 4    | 3    |\n",
    "\n",
    "最优解决方案的总价值是多少呢？\n",
    "\n",
    "由于$n = 4$且$C = 6$，因此背包算法中的数组$A$可以用一个$5$列（对应于$i = 0, 1,…, 4$）$7$行（对应于$c = 0, 1,…, 6$）的表格形象地说明。\n",
    "最终的数组值如图所示。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03e8626a-061a-4715-bdd4-5df9a1c026b4",
   "metadata": {},
   "source": [
    "![背包问题二维数组](knapsack1.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d580f8f4-375c-45a8-b536-d28e1cf35444",
   "metadata": {},
   "source": [
    "背包算法（按照从左到右的顺序）可以计算这些项。在同一列中，背包算法则是按照从下到上的顺序进行计算。  \n",
    "为了填充第$i$列的某一项，算法把它左边紧邻的那个项（对应于情况1）和“$v_i$与左侧向下$s_i$行的那一项之和”进行比较，\n",
    "并取两者中较大的那个。  \n",
    "对于$A[2][5]$而言，更好的选择是跳过后者直接选择左边紧邻的“$3$”。  \n",
    "但对于$A[3][5]$而言，更好的选择是包含物品$3$，也就是选择$4$（$v_3$）加上$2$（左侧向下$s_i$行的那一项，即$A[2][3]$）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ef3bc819-2c2c-40d5-8e0f-caaf454fe497",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最大价值为: 8\n"
     ]
    }
   ],
   "source": [
    "# 示例\n",
    "weights = [4, 3, 2, 3]  # 物品重量\n",
    "values = [3, 2, 4, 4]   # 物品价值\n",
    "capacity = 6            # 背包容量\n",
    "\n",
    "max_value = knapsack(weights, values, capacity)\n",
    "print(f\"最大价值为: {max_value}\")  # 输出: 最大价值为: 8"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfe6e9be-dea4-4f42-a15a-328f901b309d",
   "metadata": {},
   "source": [
    "**重建**\n",
    "\n",
    "背包算法只计算最优解决方案的总价值，并不产生最优解决方案本身。  \n",
    "我们可以通过回溯填充数组A的过程来重新构建一个最优解决方案。  \n",
    "这个重建算法以右上角的最大子问题为起点，确认使用推导公式的某种情况来计算$A[n][C]$。  \n",
    "如果是第一种情况，算法就忽略物品$n$，并从$A[n−1][C]$这一项继续重建过程。  \n",
    "如果是第二种情况，算法就在它的解决方案中包含物品$n$，并从$A[n−1][C–s_n]$这一项继续重建过程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "beaa545b-9a60-4360-9b24-dba56dbadc96",
   "metadata": {},
   "source": [
    "**背包问题的重建算法**\n",
    "\n",
    "**输入**：背包算法为物品价值是$v_1,v_2,…,v_n$，物品大小是$s_1,s_2,…,s_n$和背包容量是$C$的背包问题所计算产生的数组$A$。\n",
    "\n",
    "**输出**：一个最优的背包问题解决方案。\n",
    "\n",
    "---\n",
    "\n",
    "$S := \\emptyset$ // 最优解决方案中的物品  \n",
    "$c := C$         // 剩余的容量  \n",
    "**for** i = n downto 1 **do**  \n",
    "&emsp;&emsp;**if** $s_i \\le c$ and $A[i-1][c-s_i] + v_i \\ge A[i-1][c]$ **then**  \n",
    "&emsp;&emsp;&emsp;&emsp;$S := S \\cup \\{i\\}$   // 第一种情况获胜，包含$i$  \n",
    "&emsp;&emsp;&emsp;&emsp;$c := c − s_i$        // 为它保留空间  \n",
    "&emsp;&emsp;// **else**跳过i，容量保持不变  \n",
    "**return** $S$\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4e13aeca-090a-4309-9ad9-28c8d2458e78",
   "metadata": {},
   "outputs": [],
   "source": [
    "def knapsack_with_items(weights, values, capacity):\n",
    "    assert len(weights) == len(values), \"物品价值数组长度必须等于物品大小数组\"\n",
    "    n = len(weights)\n",
    "    A = [[0 for _ in range(capacity+1)] for _ in range(n+1)]\n",
    "    for c in range(capacity+1):\n",
    "        A[0][c] = 0\n",
    "\n",
    "    for i in range(1, n+1):\n",
    "        for c in range(0, capacity+1):\n",
    "            if weights[i-1] > c:\n",
    "                A[i][c] = A[i-1][c]\n",
    "            else:\n",
    "                A[i][c] = max(A[i-1][c], A[i-1][c-weights[i-1]] + values[i-1])\n",
    "\n",
    "    # 回溯找出选择的物品\n",
    "    S = []\n",
    "    c = capacity\n",
    "    for i in range(n, 0, -1):\n",
    "        if weights[i-1] <= c and A[i-1][c-weights[i-1]] + values[i-1] > A[i-1][c]:\n",
    "            S.append(i)  # 添加物品索引，这里是从1开始计算的索引\n",
    "            c -= weights[i-1]\n",
    "    \n",
    "    return A[n][capacity], S"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "268d00b4-0bec-40e7-8ff1-49e09f14b999",
   "metadata": {},
   "source": [
    "对上图所示的数组进行回溯产生最优解决方案{3,4}，如图所示。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be306d4e-f630-4946-bbc0-5c447ca703dc",
   "metadata": {},
   "source": [
    "![背包问题二维数组](knapsack2.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "90dc597c-5580-44e3-8e4a-e8ac8433f981",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最大价值为: 8\n",
      "选择的物品索引: [4, 3]\n"
     ]
    }
   ],
   "source": [
    "# 示例\n",
    "weights = [4, 3, 2, 3]  # 物品重量\n",
    "values = [3, 2, 4, 4]   # 物品价值\n",
    "capacity = 6            # 背包容量\n",
    "\n",
    "max_value, selected_items = knapsack_with_items(weights, values, capacity)\n",
    "print(f\"最大价值为: {max_value}\")          # 输出: 最大价值为: 8\n",
    "print(f\"选择的物品索引: {selected_items}\")  # 输出: 选择的物品索引: [3, 2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9ea500b-92f4-4066-9a8e-145bb4148e3e",
   "metadata": {},
   "source": [
    "### 参考文档\n",
    "《算法详解（卷3）——贪心算法和动态规划》：4.5 背包问题"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
